package com.topvision.face.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import com.kernal.demo.plateid.R;
import com.topvision.face.FRActivity;
import com.topvision.face.VideoCache;

import java.io.FileDescriptor;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

//import com.smartvision.smartcamera.provider.ARContext;

@SuppressLint("NewApi")
public class VideoPlayerView extends LinearLayout implements
		SurfaceTextureListener {

	/*
	 * public VideoPlayerView(String url, Context context){ this(context, null);
	 * 
	 * this.url = url; }
	 */
	public VideoPlayerView(List<String> urlList, Context context) {
		this(context, null);
		_id = 0;
		this.urlList = urlList;
	}

	public void initUrlList(List<String> urlList) {
		_id = 0;
		this.urlList = urlList;
	}

	public VideoPlayerView(Context context) {
		this(context, null);
	}

	public VideoPlayerView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	private FRActivity activity;

	@SuppressLint("NewApi")
	public VideoPlayerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		activity = (FRActivity) context;
		LayoutInflater.from(context).inflate(R.layout.video_player, this, true);

		initFields();
		bindListeners();
	}

	public void release() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (player != null) {
			player.release();
			player = null;
		}
		released = true;
		// urlList = null;
	}

	public boolean isInPlayList(List<String> _urlList) {
		boolean in = false;
		if (_id <= urlList.size() - 1) {
			if (!_urlList.isEmpty() && !urlList.isEmpty()) {
				String _url0 = _urlList.get(0);
				String url0 = urlList.get(0);
				if (_url0.equals(url0)) {
					in = true;
				}
			}
		}

		return in;
	}

	private void initFields() {
		// r1 = (RelativeLayout) findViewById(R.id.rl2);
		// r2 = (RelativeLayout) findViewById(R.id.rl1);

		pauseImg = (ImageView) findViewById(R.id.pauseImg);
		loadingBar = (ProgressBar) findViewById(R.id.playbar);
		loadingBar.setMax(ProgressMax);

		playBtn = (ImageButton) findViewById(R.id.videoPlayBtn);
		playBtn.setImageResource(R.mipmap.play_main);
		playBtn.setEnabled(false);

		seekbar = (SeekBar) findViewById(R.id.videoPlaySeekbar);
		playerSurface = (TextureView) findViewById(R.id.mSurfaceView);

		timeTip = (TextView) findViewById(R.id.video_time);
		// startTimeTv = (TextView)findViewById(R.id.video_start_time);
		// totalTimeTv = (TextView)findViewById(R.id.video_end_time);
		playerSurface.setSurfaceTextureListener(this);

		myToast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT);

	}

	private void bindListeners() {
		playerSurface.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!hideCtrls) {
					// r1.setVisibility(View.INVISIBLE);
					// r2.setVisibility(View.INVISIBLE);
					findViewById(R.id.rl1).setVisibility(View.INVISIBLE);
					hideCtrls = true;
				} else {
					// r1.setVisibility(View.VISIBLE);
					// r2.setVisibility(View.VISIBLE);
					findViewById(R.id.rl1).setVisibility(View.VISIBLE);
					hideCtrls = false;
				}
			}
		});
		playBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (player.isPlaying()) {
					player.pause();
					playBtn.setImageResource(R.mipmap.play_main);
				} else {
					player.start();
					playBtn.setImageResource(R.mipmap.stop);
				}
			}
		});

		seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

				// 计算进度条需要前进的位置数据大小
				int value = (int) (seekbar.getProgress() * player.getDuration() / seekbar
						.getMax());
				player.seekTo(value);

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
										  boolean fromUser) {

			}
		});
	}

	/**
	 * 播放下一个视频
	 */
	private void forward() {
		if (urlList == null || urlList.isEmpty()) {
			return;
		}
		// postSize = 0;
		if (_id >= urlList.size() - 1) {
			_id = urlList.size() - 1;
			// Toast.makeText(this, "已经是最后一个", Toast.LENGTH_SHORT).show();
			showToast("播放结束");
			isPlaying = false;
			activity.mHandler.sendEmptyMessage(FRActivity.PLAY_FINISH_STATUS);
			return;
		} else {
			_id = _id + 1;
		}
		String url = urlList.get(_id);
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		playVideo(url);
	}

	private Toast myToast;

	private void showToast(String text) {
		myToast.setText(text);
		myToast.show();
	}

	private final static String audio_exts = "mp3,wma,wav";

	@SuppressLint("NewApi")
	private void playVideo(String url) {
		try {
			isPlaying = true;
			String extendName = url.substring(url.lastIndexOf(".") + 1);
			seekbar.setProgress(0);
			timeTip.setText("00:00 / 01:00 ");
			if (audio_exts.contains(extendName)) {
				activity.mHandler
						.sendEmptyMessage(FRActivity.AUDIO_PLAY_STATUS);
				playAudio(url);
			} else {
				activity.mHandler
						.sendEmptyMessage(FRActivity.MEDIA_PLAY_STATUS);
				// Create a new media player and set the listeners
				if (player == null) {
					player = new MediaPlayer(/*
											 * ARContext.getCurrentContext(),
											 * true
											 */);
				}
				player.reset(); // 恢复播放器默认
				if (!setLocalResSourceOnExist(url)) {
					player.setDataSource(url); // 设置播放路径
				}
				player.prepareAsync(); // 准备播放
				Surface surf = new Surface(playerSurface.getSurfaceTexture());
				player.setSurface(surf);
				player.setOnPreparedListener(new PreparedListener());
				player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
					public void onBufferingUpdate(MediaPlayer mp, int percent) {
						mCurrentBufferPercentage = percent;
					}
				});
				player.setOnCompletionListener(new ComplementionListener());
			}

		} catch (Exception e) {
			Log.e("playeVideo", "error: " + e.getMessage(), e);
		}
	}

	@SuppressLint("NewApi")
	private void playAudio(String url) {
		try {

			// Create a new media player and set the listeners
			if (player == null) {
				player = new MediaPlayer(/* ARContext.getCurrentContext(), true */);
			}
			player.reset(); // 恢复播放器默认
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			if (!setLocalResSourceOnExist(url)) {
				player.setDataSource(url); // 设置播放路径
			}

			player.prepareAsync(); // 准备播放
			// Surface surf = new Surface(playerSurface.getSurfaceTexture());
			// player.setSurface(surf);
			player.setOnPreparedListener(new PreparedListener());
			player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
				public void onBufferingUpdate(MediaPlayer mp, int percent) {
					mCurrentBufferPercentage = percent;
				}
			});
			player.setOnCompletionListener(new ComplementionListener());

		} catch (Exception e) {
			Log.e("playeVideo", "error: " + e.getMessage(), e);
		}
	}

	private String getUrlResName(String url) {
		int index = url.lastIndexOf("/");
		String key = url.substring(index + 1);

		return key;
	}

	private boolean setLocalResSourceOnExist(String url) {
		boolean success = false;
		if (VideoCache.getInstance().isResExists(url)) {
			String name = getUrlResName(url);
			AssetFileDescriptor afd;
			try {
				afd = VideoCache.getAssetManager().openFd(name);
				FileDescriptor fd = afd.getFileDescriptor();
				player.setDataSource(fd, afd.getStartOffset(), afd.getLength());
				success = true;
				Log.i("cache", "load res from local: " + url);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return success;
	}

	private String durationTime = null;

	private class PreparedListener implements OnPreparedListener {

		@Override
		public void onPrepared(MediaPlayer player) {
			playBtn.setEnabled(true);
			playBtn.setImageResource(R.mipmap.stop);
			pauseImg.setVisibility(View.GONE);
			loadingBar.setVisibility(View.GONE);
			// totalTimeTv.setText(toTime(player.getDuration()));
			durationTime = " / " + toTime(player.getDuration());
			timeTip.setText("00:00 " + durationTime);
			mTimer = new Timer();
			mTimerTask = genTimerTask();
			handleProgress.sendEmptyMessage(START_TIMER);
			player.start();
		}

	}

	private class ComplementionListener implements OnCompletionListener {
		@Override
		public void onCompletion(MediaPlayer mp) {
			seekbar.setProgress(seekbar.getMax());
			seekbar.setSecondaryProgress(seekbar.getMax());
			forward();
		}
	}

	private Timer mTimer = null;

	private TimerTask genTimerTask() {
		return new TimerTask() {
			@Override
			public void run() {
				if (player == null || seekbar == null)
					return;
				if (player.isPlaying() && seekbar.isPressed() == false) {
					handleProgress.sendEmptyMessage(UPDATE_SEEKBAR);
					Log.i("seekbar", "send msg to handler...");
				}
			}
		};
	}

	private TimerTask mTimerTask = null;

	private final Handler handleProgress = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case START_TIMER:
				if (!released) {
					mTimer.schedule(mTimerTask, 0, 300);
				}
				break;
			case UPDATE_SEEKBAR:
				if (!released && player.isPlaying()) {
					long position = player.getCurrentPosition();
					long duration = player.getDuration();

					if (duration > 0) {
						long pos = seekbar.getMax() * position / duration;
						seekbar.setProgress((int) pos);
						// startTimeTv.setText(toTime(position));
						timeTip.setText(toTime(position)
								+ (durationTime == null ? " / 01:00"
										: durationTime));
						Log.i("seekbar", pos + "");
					}
				}

				break;
			default:
				break;
			}

		};
	};

	// private OnBufferingUpdateListener mBufferingUpdateListener;

	/**
	 * 时间格式转换
	 * 
	 * @param time
	 * @return
	 */
	public String toTime(long time) {

		time /= 1000;
		long minute = time / 60;
		long second = time % 60;
		minute %= 60;
		return String.format("%02d:%02d", minute, second);
	}

	public boolean isPlaying() {
		return isPlaying;
	}

	private ImageView pauseImg;
	private ProgressBar loadingBar;
	private ImageButton playBtn;
	private SeekBar seekbar;
	private TextureView playerSurface;
	// private RelativeLayout /*r1, */r2;
	// private TextView startTimeTv, totalTimeTv;
	private TextView timeTip;
	private boolean hideCtrls = false;
	private boolean released = false;
	private boolean isPlaying = false;
	private static int ProgressMax = 1000;

	// 播放器
	private MediaPlayer player;

	private List<String> urlList;
	private static int _id = -1;

	// private String url;
	private int mCurrentBufferPercentage = 0;

	private static final int START_TIMER = 1;
	private static final int UPDATE_SEEKBAR = 2;

	@Override
	public void onSurfaceTextureAvailable(SurfaceTexture surf, int arg1,
										  int arg2) {
		if (_id < 0) {
			_id = 0;
		}
		if (urlList != null && !urlList.isEmpty()) {
			playVideo(urlList.get(_id));
		}
	}

	@Override
	public boolean onSurfaceTextureDestroyed(SurfaceTexture surf) {
		return false;
	}

	@Override
	public void onSurfaceTextureSizeChanged(SurfaceTexture surf, int arg1,
											int arg2) {

	}

	@Override
	public void onSurfaceTextureUpdated(SurfaceTexture surf) {

	}
}
